package com.android.exchangeapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.exchangeapp.modle.ExchangeManager
import kotlinx.coroutines.launch

/**
 * Created by Matt on 2023/10/31.
 **/
class SupportListActivity : AppCompatActivity() {
    private var mListView: RecyclerView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list)
        val selectItemKey = SelectCurrencyContract.getSelectKey(intent)
        mListView = findViewById(R.id.list)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        lifecycleScope.launch {
            val dataList = ExchangeManager.getSupportCurrency(this@SupportListActivity)
            mListView?.adapter = SupportListAdapter(dataList) {
                setResult(RESULT_OK, SelectCurrencyContract.createData(it))
                finish()
            }.apply { setCheckPosition(dataList.indexOfFirst { supportCurrency ->  supportCurrency.key == selectItemKey}) }
            mListView?.layoutManager = LinearLayoutManager(this@SupportListActivity)
            mListView?.addItemDecoration(DividerItemDecoration(this@SupportListActivity, DividerItemDecoration.VERTICAL))
        }
    }
}